import React, { useState, useEffect, useMemo } from 'react';
import { Table, Input, Button, Space, Dropdown, Tag, Tooltip, Modal, message, DatePicker, Select, InputNumber, Row, Col, Switch } from 'antd';
import type { TableProps as AntTableProps } from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  ExportOutlined,
  SettingOutlined,
  FileExcelOutlined,
  FilePdfOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import type { TableProps, TableState } from './types';

const { Option } = Select;

const AdvancedTable = <T extends Record<string, unknown>>(props: TableProps<T>) => {
  const {
    columns,
    dataSource,
    loading = false,
    rowKey = 'id',
    rowSelection,
    pagination,
    size = 'middle',
    showHeader = true,
    scroll,
    title,
    footer,
    expandable,
    searchFields = [],
    onSearch,
    onExport,
    batchActions = [],
    columnSettings,
    refresh,
    extra,
    rowClassName,
    onRow,
    onChange,
    stickySettings,
    columnPinning,
  } = props;

  const [state, setState] = useState<TableState>({
    searchText: '',
    searchParams: {},
    filteredInfo: {},
    sortedInfo: {},
    selectedRowKeys: rowSelection?.selectedRowKeys || [],
    selectedRows: [],
    visibleColumns: columnSettings?.defaultVisibleColumns || columns.map(col => col.key),
    columnSettingsVisible: false,
    pinnedColumns: columnPinning?.defaultPinnedColumns || { left: [], right: [] },
    columnPinningVisible: false,
  });

  // 同步外部选中的行
  useEffect(() => {
    if (rowSelection?.selectedRowKeys) {
      setState(prev => ({
        ...prev,
        selectedRowKeys: rowSelection.selectedRowKeys!,
      }));
    }
  }, [rowSelection?.selectedRowKeys]);

  // 处理搜索
  const handleSearch = (searchParams: Record<string, unknown>) => {
    setState(prev => ({
      ...prev,
      searchParams: { ...prev.searchParams, ...searchParams },
    }));
    onSearch?.({ ...state.searchParams, ...searchParams });
  };

  // 处理重置搜索
  const handleResetSearch = () => {
    setState(prev => ({
      ...prev,
      searchText: '',
      searchParams: {},
      filteredInfo: {},
    }));
    onSearch?.({});
  };

  // 处理表格变化
  const handleTableChange: AntTableProps['onChange'] = (paginationConfig, filters, sorter) => {
    console.log('1. Table 组件触发分页 onChange 事件:', {
      current: paginationConfig?.current,
      pageSize: paginationConfig?.pageSize
    });

    setState(prev => ({
      ...prev,
      filteredInfo: filters,
      sortedInfo: sorter,
    }));

    // 直接调用外部的 onChange 回调
    if (onChange && paginationConfig) {
      onChange(paginationConfig as TablePagination, filters, sorter);
    }
  };

  // 处理行选择
  const handleRowSelection = (selectedRowKeys: React.Key[], selectedRows: T[]) => {
    setState(prev => ({
      ...prev,
      selectedRowKeys,
      selectedRows,
    }));
    rowSelection?.onChange?.(selectedRowKeys, selectedRows);
  };

  // 处理导出
  const handleExport = (format: 'csv' | 'excel' | 'pdf') => {
    onExport?.(format);
    message.success(`正在导出 ${format.toUpperCase()} 格式数据...`);
  };

  // 处理列设置
  const handleColumnSettings = (visibleColumns: string[]) => {
    setState(prev => ({
      ...prev,
      visibleColumns,
    }));
    columnSettings?.onColumnsChange?.(visibleColumns);
  };

  // 处理列固定
  const handleColumnPinning = (columnKey: string, position: 'left' | 'right' | null) => {
    setState(prev => {
      const newPinnedColumns = { ...prev.pinnedColumns };

      // 从当前位置移除
      if (newPinnedColumns.left?.includes(columnKey)) {
        newPinnedColumns.left = newPinnedColumns.left.filter(key => key !== columnKey);
      }
      if (newPinnedColumns.right?.includes(columnKey)) {
        newPinnedColumns.right = newPinnedColumns.right.filter(key => key !== columnKey);
      }

      // 添加到新位置
      if (position) {
        if (!newPinnedColumns[position]) {
          newPinnedColumns[position] = [];
        }
        newPinnedColumns[position]!.push(columnKey);
      }

      return {
        ...prev,
        pinnedColumns: newPinnedColumns,
      };
    });
    columnPinning?.onPinnedColumnsChange?.(state.pinnedColumns);
  };

  // 渲染工具栏（整合所有操作到表格title中）
  const renderToolbar = () => {
    const menuItems = [
      {
        key: 'csv',
        label: (
          <span onClick={() => handleExport('csv')}>
            <FileTextOutlined /> 导出 CSV
          </span>
        ),
      },
      {
        key: 'excel',
        label: (
          <span onClick={() => handleExport('excel')}>
            <FileExcelOutlined /> 导出 Excel
          </span>
        ),
      },
      {
        key: 'pdf',
        label: (
          <span onClick={() => handleExport('pdf')}>
            <FilePdfOutlined /> 导出 PDF
          </span>
        ),
      },
    ];

    const settingsMenuItems = [
      {
        key: 'stickyHeader',
        label: (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: 160 }}>
            <span>固定表头</span>
            <Switch
              size="small"
              checked={stickySettings?.enabled && stickySettings.header}
              onChange={(checked) => {
                if (stickySettings?.enabled !== undefined && stickySettings.onHeaderChange) {
                  stickySettings.onHeaderChange(checked);
                }
              }}
            />
          </div>
        ),
      },
      {
        key: 'columnPinning',
        label: (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: 160 }}>
            <span>固定列</span>
            <Button
              type="text"
              size="small"
              icon={<SettingOutlined />}
              onClick={() => setState(prev => ({ ...prev, columnPinningVisible: true }))}
            />
          </div>
        ),
      },
      {
        key: 'columnSettings',
        label: (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: 160 }}>
            <span>显示列</span>
            <Button
              type="text"
              size="small"
              icon={<SettingOutlined />}
              onClick={() => setState(prev => ({ ...prev, columnSettingsVisible: true }))}
            />
          </div>
        ),
      },
    ];

    return (
      <div style={{ padding: '16px 20px', background: '#fff' }}>
        {/* 搜索条件区域 */}
        {searchFields.length > 0 && (
          <div style={{
            marginBottom: 16,
            padding: '16px',
            background: '#fafafa',
            borderRadius: '6px',
            border: '1px solid #f0f0f0'
          }}>
            <div style={{
              fontSize: '14px',
              fontWeight: 500,
              color: '#262626',
              marginBottom: '12px',
              display: 'flex',
              alignItems: 'center',
              gap: '6px'
            }}>
              <SearchOutlined style={{ color: '#1890ff' }} />
              搜索条件
            </div>
            <Row gutter={[16, 12]} align="middle">
              {searchFields.slice(0, 4).map(field => (
                <Col key={field.key}>
                  <Space direction="vertical" size={4}>
                    <span style={{
                      fontSize: '13px',
                      color: '#595959',
                      fontWeight: 500
                    }}>
                      {field.label}
                    </span>
                    {field.type === 'input' && (
                      <Input
                        placeholder={field.placeholder || `请输入${field.label}`}
                        allowClear={field.allowClear ?? true}
                        onChange={(e) => handleSearch({ [field.key]: e.target.value })}
                        style={{ width: 160 }}
                      />
                    )}
                    {field.type === 'select' && field.options && (
                      <Select
                        placeholder={field.placeholder || `请选择${field.label}`}
                        allowClear={field.allowClear ?? true}
                        style={{ width: 160 }}
                        onChange={(value) => handleSearch({ [field.key]: value })}
                      >
                        {field.options.map(option => (
                          <Option key={option.value} value={option.value}>
                            {option.label}
                          </Option>
                        ))}
                      </Select>
                    )}
                    {field.type === 'date' && (
                      <DatePicker
                        placeholder={field.placeholder || `请选择${field.label}`}
                        style={{ width: 180 }}
                        onChange={(date, dateString) => handleSearch({ [field.key]: dateString })}
                      />
                    )}
                    {field.type === 'number' && (
                      <InputNumber
                        placeholder={field.placeholder || `请输入${field.label}`}
                        style={{ width: 140 }}
                        onChange={(value) => handleSearch({ [field.key]: value })}
                      />
                    )}
                  </Space>
                </Col>
              ))}
              <Col>
                <div style={{ marginTop: '19px' }}>
                  <Space size={8}>
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      onClick={() => onSearch?.(state.searchParams)}
                    >
                      搜索
                    </Button>
                    <Button
                      icon={<ReloadOutlined />}
                      onClick={handleResetSearch}
                    >
                      重置
                    </Button>
                  </Space>
                </div>
              </Col>
            </Row>
          </div>
        )}

        {/* 批量操作区域 */}
        {batchActions.length > 0 && state.selectedRowKeys.length > 0 && (
          <div style={{
            marginBottom: 16,
            padding: '12px 16px',
            background: '#e6f7ff',
            borderRadius: '6px',
            border: '1px solid #91d5ff'
          }}>
            <Space align="center" wrap>
              <Tag color="blue" style={{ fontWeight: 500 }}>
                已选择 {state.selectedRowKeys.length} 项
              </Tag>
              {batchActions.map(action => (
                <Button
                  key={action.key}
                  type={action.danger ? 'primary' : 'default'}
                  danger={action.danger}
                  icon={action.icon}
                  size="small"
                  onClick={() => action.onClick(state.selectedRows)}
                >
                  {action.label}
                </Button>
              ))}
              <Button
                size="small"
                onClick={() => handleRowSelection([], [])}
              >
                取消选择
              </Button>
            </Space>
          </div>
        )}

        {/* 主工具栏 */}
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          paddingTop: searchFields.length > 0 || (batchActions.length > 0 && state.selectedRowKeys.length > 0) ? 0 : 0
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            {title && (
              <div style={{
                fontSize: '16px',
                fontWeight: 600,
                color: '#262626'
              }}>
                {title()}
              </div>
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {extra}
            </div>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {refresh && (
              <Button
                icon={<ReloadOutlined />}
                onClick={refresh}
              >
                刷新
              </Button>
            )}

            {(stickySettings?.enabled || columnPinning?.enabled || columnSettings?.enabled) && (
              <Dropdown menu={{ items: settingsMenuItems }} placement="bottomRight" trigger={['click']}>
                <Button
                  icon={<SettingOutlined />}
                >
                  设置
                </Button>
              </Dropdown>
            )}

            {onExport && (
              <Dropdown menu={{ items: menuItems }} placement="bottomRight">
                <Button
                  icon={<ExportOutlined />}
                >
                  导出
                </Button>
              </Dropdown>
            )}
          </div>
        </div>
      </div>
    );
  };

  // 处理列显示/隐藏
  const handleColumnVisibility = (columnKey: string, visible: boolean) => {
    const newVisibleColumns = visible
      ? [...state.visibleColumns, columnKey]
      : state.visibleColumns.filter(key => key !== columnKey);
    handleColumnSettings(newVisibleColumns);
  };

  // 渲染列设置对话框
  const renderColumnSettings = () => {
    return (
      <Modal
        title="列显示设置"
        open={state.columnSettingsVisible}
        onCancel={() => setState(prev => ({ ...prev, columnSettingsVisible: false }))}
        footer={[
          <Button
            key="reset"
            onClick={() => {
              const allColumnKeys = columns.map(col => col.key);
              handleColumnSettings(allColumnKeys);
            }}
          >
            全部显示
          </Button>,
          <Button
            key="close"
            type="primary"
            onClick={() => setState(prev => ({ ...prev, columnSettingsVisible: false }))}
          >
            确定
          </Button>
        ]}
        width={600}
      >
        <div style={{ maxHeight: 400, overflowY: 'auto' }}>
          <Row gutter={[16, 16]}>
            {columns.map(column => (
              <Col span={12} key={column.key}>
                <div style={{
                  display: 'flex',
                  alignItems: 'center',
                  padding: '12px',
                  background: '#fafafa',
                  border: '1px solid #f0f0f0',
                  borderRadius: '6px',
                  cursor: 'pointer'
                }}
                onClick={() => handleColumnVisibility(column.key, !state.visibleColumns.includes(column.key))}
                >
                  <Switch
                    checked={state.visibleColumns.includes(column.key)}
                    onChange={(checked) => handleColumnVisibility(column.key, checked)}
                    size="small"
                    style={{ marginRight: 12 }}
                  />
                  <div style={{ flex: 1 }}>
                    <div style={{
                      fontSize: '14px',
                      fontWeight: 500,
                      color: '#262626',
                      marginBottom: column.description ? '4px' : 0
                    }}>
                      {column.title}
                    </div>
                    {column.description && (
                      <div style={{
                        fontSize: '12px',
                        color: '#8c8c8c'
                      }}>
                        {column.description}
                      </div>
                    )}
                  </div>
                  {column.description && (
                    <Tooltip title={column.description}>
                      <div style={{
                        width: '16px',
                        height: '16px',
                        borderRadius: '50%',
                        background: '#d9d9d9',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontSize: '12px',
                        color: '#595959',
                        cursor: 'help'
                      }}>
                        ?
                      </div>
                    </Tooltip>
                  )}
                </div>
              </Col>
            ))}
          </Row>
        </div>
      </Modal>
    );
  };

  // 渲染列固定对话框
  const renderColumnPinning = () => {
    return (
      <Modal
        title="列固定设置"
        open={state.columnPinningVisible}
        onCancel={() => setState(prev => ({ ...prev, columnPinningVisible: false }))}
        footer={[
          <Button
            key="reset"
            onClick={() => {
              setState(prev => ({
                ...prev,
                pinnedColumns: { left: [], right: [] }
              }));
            }}
          >
            清除全部
          </Button>,
          <Button
            key="close"
            type="primary"
            onClick={() => setState(prev => ({ ...prev, columnPinningVisible: false }))}
          >
            确定
          </Button>
        ]}
        width={700}
      >
        <div style={{ maxHeight: 500, overflowY: 'auto' }}>
          <div style={{ display: 'flex', gap: 16 }}>
            {/* 左侧固定列 */}
            <div style={{
              flex: 1,
              padding: '16px',
              background: '#fafafa',
              borderRadius: '6px',
              border: '1px solid #f0f0f0'
            }}>
              <div style={{
                marginBottom: 16,
                fontSize: 14,
                fontWeight: 600,
                color: '#262626',
                display: 'flex',
                alignItems: 'center',
                gap: 8
              }}>
                <div style={{
                  width: 8,
                  height: 8,
                  backgroundColor: '#1890ff',
                  borderRadius: '50%'
                }} />
                左侧固定
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {columns.filter(col => !col.hidden && state.visibleColumns.includes(col.key)).map(column => (
                  <div key={`left-${column.key}`} style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '8px 12px',
                    backgroundColor: '#fff',
                    border: '1px solid #f0f0f0',
                    borderRadius: '4px',
                    cursor: 'pointer'
                  }}
                  onClick={() => handleColumnPinning(column.key, state.pinnedColumns.left?.includes(column.key) ? null : 'left')}
                  >
                    <span style={{
                      fontSize: 13,
                      color: '#262626',
                      fontWeight: state.pinnedColumns.left?.includes(column.key) ? 500 : 400
                    }}>
                      {column.title}
                    </span>
                    <Switch
                      size="small"
                      checked={state.pinnedColumns.left?.includes(column.key)}
                      onChange={(checked) => handleColumnPinning(column.key, checked ? 'left' : null)}
                    />
                  </div>
                ))}
              </div>
            </div>

            {/* 右侧固定列 */}
            <div style={{
              flex: 1,
              padding: '16px',
              background: '#fafafa',
              borderRadius: '6px',
              border: '1px solid #f0f0f0'
            }}>
              <div style={{
                marginBottom: 16,
                fontSize: 14,
                fontWeight: 600,
                color: '#262626',
                display: 'flex',
                alignItems: 'center',
                gap: 8
              }}>
                <div style={{
                  width: 8,
                  height: 8,
                  backgroundColor: '#52c41a',
                  borderRadius: '50%'
                }} />
                右侧固定
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {columns.filter(col => !col.hidden && state.visibleColumns.includes(col.key)).map(column => (
                  <div key={`right-${column.key}`} style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '8px 12px',
                    backgroundColor: '#fff',
                    border: '1px solid #f0f0f0',
                    borderRadius: '4px',
                    cursor: 'pointer'
                  }}
                  onClick={() => handleColumnPinning(column.key, state.pinnedColumns.right?.includes(column.key) ? null : 'right')}
                  >
                    <span style={{
                      fontSize: 13,
                      color: '#262626',
                      fontWeight: state.pinnedColumns.right?.includes(column.key) ? 500 : 400
                    }}>
                      {column.title}
                    </span>
                    <Switch
                      size="small"
                      checked={state.pinnedColumns.right?.includes(column.key)}
                      onChange={(checked) => handleColumnPinning(column.key, checked ? 'right' : null)}
                    />
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* 提示信息 */}
          <div style={{
            marginTop: 16,
            padding: '12px',
            backgroundColor: '#e6f7ff',
            border: '1px solid #91d5ff',
            borderRadius: '6px',
            fontSize: 12,
            color: '#0050b3',
            lineHeight: 1.5
          }}>
            💡 提示：每个列只能固定在左侧或右侧，不能同时固定在两侧。固定后可以点击开关或卡片取消固定。
          </div>
        </div>
      </Modal>
    );
  };

  // 过滤和排序后的列
  const processedColumns = useMemo(() => {
    return columns
      .filter(column => !column.hidden && state.visibleColumns.includes(column.key))
      .map(column => {
        const newColumn = { ...column };

        // 应用固定设置
        if (state.pinnedColumns.left?.includes(column.key)) {
          newColumn.fixed = 'left';
        } else if (state.pinnedColumns.right?.includes(column.key)) {
          newColumn.fixed = 'right';
        } else {
          // 保持原有的 fixed 设置
          newColumn.fixed = column.fixed;
        }

        // 应用排序状态
        if (column.sorter) {
          newColumn.sortOrder = state.sortedInfo.field === column.dataIndex ? state.sortedInfo.order : null;
        }

        // 应用筛选状态
        if (column.filters) {
          newColumn.filteredValue = state.filteredInfo[column.dataIndex] || null;
        }

        return newColumn;
      });
  }, [columns, state.visibleColumns, state.sortedInfo, state.filteredInfo, state.pinnedColumns]);

  // 处理分页
  const processedPagination = pagination === false ? false : {
    current: pagination?.current || 1,
    pageSize: pagination?.pageSize || 10,
    total: pagination?.total || dataSource.length,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
    // 移除单独的 onChange 处理器，让所有分页事件都通过 Table 的 onChange 统一处理
  };

  // 简单的滚动配置
  const tableScroll = useMemo(() => {
    if (scroll) {
      return {
        ...scroll,
        x: scroll.x || 1200, // 给一个合适的横向宽度
      };
    }
    return {
      x: 1200,
    };
  }, [scroll]);

  return (
    <>
      <div style={{
        backgroundColor: '#ffffff',
        borderRadius: '6px',
        boxShadow: '0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09)',
        border: '1px solid #f0f0f0'
      }}>
        <Table<T>
          columns={processedColumns}
          dataSource={dataSource}
          loading={loading}
          rowKey={rowKey}
          rowSelection={rowSelection ? {
            ...rowSelection,
            selectedRowKeys: state.selectedRowKeys,
            onChange: handleRowSelection,
          } : undefined}
          pagination={processedPagination}
          bordered={false}
          size={size}
          showHeader={showHeader}
          scroll={tableScroll}
          title={renderToolbar}
          footer={footer}
          expandable={expandable}
          rowClassName={rowClassName}
          onRow={onRow}
          onChange={handleTableChange}
        />
      </div>

      {renderColumnSettings()}
      {renderColumnPinning()}
    </>
  );
};

export default AdvancedTable;